package com.sailing.xjpb.web.base.converter;

import com.sailing.xjpb.common.exception.ConvertException;
import org.apache.commons.lang3.StringUtils;
import org.springframework.core.convert.converter.Converter;
import org.springframework.lang.Nullable;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.Optional;

/**
 * 字符串转日期出错
 *
 * @author YaoWei
 * createDate: 2020/12/21 11:44
 */
public class StringToDateConverter implements Converter<String, Date> {

    private static final String[] DEFAULT_DATE_PATTERNS = new String[]{"yyyyMMdd", "yyyy-MM-dd", "yyyyMMddHHmmss",
            "yyyy-MM-dd HH:mm:ss", "yyyy-MM-dd HH:mm:ss.sss"};

    private final String[] datePatterns;

    public StringToDateConverter() {
        this.datePatterns = DEFAULT_DATE_PATTERNS;
    }

    public StringToDateConverter(String[] datePatterns) {
        this.datePatterns = datePatterns;
    }


    @Override
    public Date convert(@Nullable String source) {
        if (StringUtils.isEmpty(source)) {
            return null;
        }
        try {
            String datePattern = getDatePattern(source);
            SimpleDateFormat format = new SimpleDateFormat(datePattern);
            return format.parse(source);
        } catch (ParseException e) {
            throw new ConvertException(String.format("parser %s 转换为时间格式参数失败！", source), e);
        }
    }

    /**
     * 获取日期格式
     *
     * @param source 日期字符串
     * @return 日期格式
     */
    private String getDatePattern(String source) {
        Optional<String> datePattern =
                Arrays.stream(datePatterns).filter(e -> e.length() == source.length()).findFirst();
        return datePattern.orElseThrow(() -> new ConvertException("不支持转换的日期格式：" + source));
    }
}